const {buildOptimizer} = require('@angular-devkit/build-optimizer');
const node = require('rollup-plugin-node-resolve');
const path = require('path');
const {ivyEnabled} = require(getIvyEnabledHelperPath());

console.info(`Processing rollup bundle in ${ivyEnabled ? 'Ivy' : 'View Engine'} mode.`);

const buildOptimizerPlugin = {
  name: 'build-optimizer',
  transform: (content, id) => {
    const {content: code, sourceMap: map} = buildOptimizer({
      content,
      inputFilePath: id,
      emitSourceMap: true,
      // Always assume side-effect free source files, except for the autogenerated
      // module index file. The bootstrap module call should not be eliminated.
      isSideEffectFree: !id.endsWith('_autogenerated_module_index.mjs'),
      isAngularCoreFile: false,
    });
    if (!code) {
      return null;
    }
    if (!map) {
      throw new Error('No sourcemap produced by build optimizer');
    }
    return {code, map};
  },
};

module.exports = {
  plugins: [
    buildOptimizerPlugin,
    node({
      mainFields: ivyEnabled ?
          ['es2015_ivy_ngcc', 'module_ivy_ngcc','es2015', 'module'] :
          ['es2015', 'module'],
    }),
  ],
};

function getIvyEnabledHelperPath() {
  const parts = path.normalize(__dirname).split(path.sep);
  const binIndex = parts.indexOf('bin');

  if (binIndex === -1) {
    throw Error('Cannot resolve Ivy helper path.');
  }

  return path.join(parts.slice(0, binIndex).join(path.sep), 'bin/tools/angular_ivy_enabled');
}
